package com.zlzvip.android.common.http.qiniu;

import android.content.Context;
import android.text.TextUtils;

import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.SLog;
import com.qiniu.android.common.ServiceAddress;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.zlzvip.android.account.UrlCenter;
import com.zlzvip.android.common.http.MyHttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 七牛云文件上传工具
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2017/1/16 17:42
 * @Version: 1.0.0
 */
public class QiniuFileUploader {
    // 无效的token
    public static final int ERR_INVALIDE_TOKEN = 0X011;
    // 文件上传失败
    public static final int ERR_FAILURE = 0X012;


    public static final void uploadFile(Context context, final String srcFilePath, final DataRequestListener listener) {
        IHttpRequest request = new MyHttpRequest(context);
        request.get(UrlCenter.QINIU_TOKEN, null, new DataRequestListener<String>(String.class) {

            @Override
            public void onSuccess(String acct) {
                super.onSuccess(acct);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(acct);
                    String qiniuToken = jsonObject.optString("value");
                    uploadFile(qiniuToken, srcFilePath, listener);


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                listener.onFailure(t, errorNo, strMsg);
            }
        });
    }

    private static void uploadFile(String qiniuToken, String srcFilePath, final DataRequestListener listener) {
        if (TextUtils.isEmpty(qiniuToken)) {
            listener.onFailure(new UnknownError(), ERR_INVALIDE_TOKEN, "token 失效");
            return;
        }
        final String filePath;
        if (srcFilePath.startsWith("file://")) {
            filePath = srcFilePath.substring(("file://".length()));
        } else {
            filePath = srcFilePath;
        }

        UploadManager manager = getUploadManager();
        final String key = System.currentTimeMillis() + "";
        manager.put(filePath, key, qiniuToken,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        SLog.e("vivi", key + ",\r\n " + info + ",\r\n " + res);
                        if (info.isOK()) {
                            String iconUrl = UrlCenter.OUTER_LINK + key;
                            listener.onSuccess(iconUrl);

                        } else {
                            listener.onFailure(new UnknownError(), ERR_FAILURE, "图片上传失败！");
                        }
                    }

                }, null);
    }



    private static UploadManager sUploadManager;

    public static UploadManager getUploadManager() {
        if (sUploadManager == null) {
            Zone myZone = new Zone(new ServiceAddress("http://up-z2.qiniu.com"), new ServiceAddress("http://upload-z2.qiniu.com"));
            Configuration config = new Configuration.Builder()
                    .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                    .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                    .connectTimeout(10) // 链接超时。默认10秒
                    .responseTimeout(60) // 服务器响应超时。默认60秒
                    .recorder(null)  // recorder分片上传时，已上传片记录器。默认null
//                    .recorder(recorder, keyGen)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                    .zone(myZone) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。默认 Zone.zone0
                    .build();
// 重用uploadManager。一般地，只需要创建一个uploadManager对象
            sUploadManager = new UploadManager(config);
        }

        return sUploadManager;
    }



    public static final  void test (Context context) {
        uploadFile(context, "", new DataRequestListener(Object.class) {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });

    }


}
